package gqqnbig;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class SystemHelper
{
	public static File getExecutablePath()
	{

		String workingDirectory = System.getProperty("user.dir");

		File binFile = new File(workingDirectory, "bin");
		if (binFile.exists() && (new File(workingDirectory, "src")).exists())
		{
			return binFile;
		}
		else if (isRunningFromJar())
			return getApplicationRootFolder();
		else
			return new File(workingDirectory);

	}

	public static boolean isRunningFromJar()
	{
		String className = SystemHelper.class.getName().replace('.', '/');
		String classJar = SystemHelper.class.getResource("/" + className + ".class").toString();
		return classJar.startsWith("jar:");
	}

	/**
	 * Retrieve a File representation of the folder this application is located in.
	 * 
	 * @return
	 */
	private static File getApplicationRootFolder()
	{
		try
		{
			String path = SystemHelper.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			String decodedPath;

			decodedPath = URLDecoder.decode(path, "UTF-8");

			File jarfile = new File(decodedPath);
			return jarfile.getParentFile();
		}
		catch (UnsupportedEncodingException e)
		{
			throw new RuntimeException(e);
		}
	}
}
